package org.mirrentools.attendance.console.service.impl;

import java.time.LocalDate;

import org.mirrentools.attendance.console.common.FutureUtil;
import org.mirrentools.attendance.console.common.ResultCodeEnum;
import org.mirrentools.attendance.console.common.StringUtil;
import org.mirrentools.attendance.console.entity.Report;
import org.mirrentools.attendance.console.service.ReportService;
import org.mirrentools.attendance.console.service.UidUtiil;
import org.mirrentools.attendance.console.sql.ReportSQL;

import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.assist.SQLExecute;

/**
 * Report数据服务接口的默认实现
 *
 * @author
 */
public class ReportServiceImpl implements ReportService {
  /**
   * 日志工具
   */
  private final Logger LOG = LoggerFactory.getLogger(this.getClass());
  /**
   * SQL操作语句
   */
  private ReportSQL reportSql;

  /**
   * 初始化
   *
   * @param execute
   */
  public ReportServiceImpl(SQLExecute<JDBCClient> execute) {
    super();
    this.reportSql = new ReportSQL(execute);
  }

  @Override
  public void put(MultiMap params, Handler<AsyncResult<JsonObject>> handler) {
    String uid = params.get("uid");
    if (StringUtil.isNullOrEmpty(uid)) {
      handler.handle(FutureUtil.successZero(ResultCodeEnum.C301));
      return;
    }
    String body = params.get("body");
    if (StringUtil.isNullOrEmpty(body)) {
      handler.handle(FutureUtil.successC412Zero("反馈内容不能为空!"));
      return;
    }
    int state = StringUtil.getInteger(params.get("state"), -1);
    if (state < 0 || state > 3) {
      handler.handle(FutureUtil.successC412Zero("考勤状态无效!"));
      return;
    }
    String id = params.get("id");
    int ys = StringUtil.getint(params.get("year"));
    int ms = StringUtil.getint(params.get("month"));
    int ds = StringUtil.getint(params.get("day"));
    LocalDate date = LocalDate.now();
    int year = ys <= 0 ? date.getYear() : ys;
    int month = ms <= 0 ? date.getMonthValue() : ms;
    int day = ds <= 0 ? date.getDayOfMonth() : ds;
    Report report = new Report();
    report.setId(id);
    report.setUid(uid);
    report.setYears(year);
    report.setMonths(month);
    report.setDays(day);
    report.setBody(body);
    report.setState(state);
    if (StringUtil.isNullOrEmpty(id)) {
      report.setId(UidUtiil.uid(uid, year, month, day));
    }
    reportSql.replace(report, res -> {
      if (res.succeeded()) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("执行汇报-->结果:" + res.result());
        }
        handler.handle(FutureUtil.successC200One());
      } else {
        String message = res.cause().getMessage();
        LOG.error("执行汇报-->失败:", res.cause());
        handler.handle(FutureUtil.successC500Zero("操作失败,请稍后重试!", message));
      }
    });
  }

}
